<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-form-item label="文件名称" prop="materialName">
        <ns-input v-model="formData.materialName" placeholder="请输入文件名称" />
      </el-form-item>
      <el-form-item label="文件类型" prop="materialTypeValue">
        <ns-input v-model="formData.materialTypeValue" placeholder="请输入文件类型" />
      </el-form-item>
      <el-form-item label="文件描述" prop="materialDesc">
        <ns-input
          v-model="formData.materialDesc"
          :rows="4"
          type="textarea"
          placeholder="请输入文件描述"
          @input="handleInput"
        />
      </el-form-item>
      <el-form-item label="文件上传" prop="filePath">
        <el-upload
          ref="uploadRef"
          class="upload-wrap"
          v-model:file-list="fileList"
          :action="url"
          :auto-upload="true"
          :disabled="formLoading"
          :headers="uploadHeaders"
          :limit="1"
          :on-error="submitFormError"
          :on-exceed="handleExceed"
          :on-success="submitFormSuccess"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text"> 将文件拖到此处，或 <em>点击上传</em></div>
          <!-- <template #tip>
            <div class="el-upload__tip" style="color: red">
              提示：仅允许导入 jpg、png、gif 格式文件！
            </div>
          </template> -->
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
import type { FormInstance } from 'element-plus'
import { createMaterial, updateMaterial } from '@/api/material/material'

type FormType = 'create' | 'update' | ''
defineOptions({ name: 'InfraFileForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const dialogTitle = ref('') // 弹窗的标题
const url = import.meta.env.VITE_UPLOAD_URL
//上传 Header 头
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})
const fileList = ref([]) // 文件列表
const uploadRef = ref()

const formType = ref<FormType>('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  materialName: '',
  materialTypeValue: '',
  materialType: '1', // 暂时写死资料类型
  type: 1,
  materialDesc: '',
  filePath: ''
})

const formRules = reactive({
  materialName: [{ required: true, message: '文件名称不能为空', trigger: ['blur', 'change'] }],
  // materialTypeValue: [{ required: true, message: '文件类型不能为空', trigger: ['blur', 'change'] }],
  // materialDesc: [{ required: true, message: '文件描述不能为空', trigger: ['blur', 'change'] }],
  filePath: [{ required: true, message: '请上传文件', trigger: ['blur', 'change'] }]
})
const formRef = ref<FormInstance>() // 表单 Ref

function handleInput(value) {
  // 先替换空格
  let newValue = value.replace(/\s+/g, '')
  // 更新数据
  formData.value.materialDesc = newValue
}

/** 打开弹窗 */

const open = async (type: FormType, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  // if (id) {
  //   formLoading.value = true
  //   try {
  //     formData.value = await RoleApi.getRole(id)
  //   } finally {
  //     formLoading.value = false
  //   }
  // }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value?.validate()

  // 提交请求
  formLoading.value = true
  try {
    const data = toRaw(formData.value)
    if (formType.value === 'create') {
      await createMaterial(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateMaterial(data)
      message.success(t('common.updateSuccess'))
    }
    closeDialog()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 文件上传成功处理 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitFormSuccess = (val) => {
  if (val.code != 200) {
    if (val.message) {
      message.error(val.message)
    } else {
      message.error('上传失败，请您重新上传！')
    }
    fileList.value.pop()
    formLoading.value = false
    return
  }
  formData.value.filePath = val.data.url
  formRef.value?.validateField('filePath')
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false

  formData.value = {
    id: undefined,
    materialName: '',
    materialType: '1',
    materialTypeValue: '',
    type: 1,
    materialDesc: '',
    filePath: ''
  }
  uploadRef.value?.clearFiles()
  formRef.value?.resetFields()
}

function closeDialog() {
  resetForm()
  dialogVisible.value = false
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}
</script>
<style lang="scss" scoped>
.upload-wrap {
  width: 100%;
  :deep(.el-upload-dragger) {
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
